package file;

/**
 * Author: mb25428
 * Create Date:  3/23/2013
 * 
 * Comments: this java class is for the image Upload
 * JDK version: <JDK 1.7>
 * 
 * Modified By: mb25428
 * Modified Date: 4/3/2013
 * Why&What is Modified: Add the file upload controller
 * 
 */
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.faces.application.FacesMessage;  
import javax.faces.context.FacesContext;  
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
  
import org.primefaces.event.FileUploadEvent;  
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;  

import common.FacesUtil;

import common.VideoBean;

import common.ImageBean;
import common.UserBean;
  
public class FileUploadController {  
  
	private UserBean userBean;
	private StreamedContent file;
	private StreamedContent enhanceImage;
	private ImageEnhanceController imageEnhanceController;
	
	private StreamedContent enhanceVideo;
	byte[] oriFile;
	private static String videoPath = ".avi";
	private static String enhanceVideoPath = ".avi";
	
	
	
	public StreamedContent getEnhanceVideo() {
		return enhanceVideo;
	}
	public void setEnhanceVideo(StreamedContent enhanceVideo) {
		this.enhanceVideo = enhanceVideo;
	}
	
	public String getVideoPath() {
		return videoPath;
	}
	public void setVideoPath(String videoPath) {
		FileUploadController.videoPath = videoPath;
	}
	public String getEnhanceVideoPath() {
		return enhanceVideoPath;
	}
	public void setEnhanceVideoPath(String enhanceVideoPath) {
		FileUploadController.enhanceVideoPath = enhanceVideoPath;
	}
	public UserBean getUserBean() {
		return userBean;
	}
	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}
	
	public byte[] getOriFile() {
		return oriFile;
	}
	public void setOriFile(byte[] oriFile) {
		this.oriFile = oriFile;
	}
    public ImageEnhanceController getImageEnhanceController() {
		return imageEnhanceController;
	}
	public void setImageEnhanceController(
			ImageEnhanceController imageEnhanceController) {
		this.imageEnhanceController = imageEnhanceController;
	}
	public StreamedContent getFile() {  
        return file;  
    } 
    public StreamedContent getEnhanceImage(){
    	return enhanceImage;
    }
    
    public void setEnhanceImage(StreamedContent enhanceImage) {
		this.enhanceImage = enhanceImage;
	}
    
    /**
     * @param FileUploadEvent
     * @dec Control the image upload
     * 
     */
    public void uploadImage(FileUploadEvent event){
    	HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    	//HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    	userBean =new UserBean();
		String IP = request.getRemoteAddr();
		userBean.setIP(IP);
		
		UploadedFile uploadedFile = event.getFile();
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");  
        FacesContext.getCurrentInstance().addMessage(null, msg);
        
        ImageBean oriImage = new ImageBean();
        String fileName = uploadedFile.getFileName();
        oriImage.setName(fileName);
        oriImage.setContentType(uploadedFile.getContentType());
        oriImage.setImage(uploadedFile.getContents());
        
        try {
        	ByteArrayInputStream in = new ByteArrayInputStream(uploadedFile.getContents());
        	BufferedImage bufImage = ImageIO.read(in);
        	oriImage.setBuferedImage(bufImage);
        	
        	oriImage.setWidth(bufImage.getWidth());
        	oriImage.setHeight(bufImage.getHeight());
        	
			oriImage.setImageStream(new DefaultStreamedContent(uploadedFile.getInputstream(), uploadedFile.getContentType(), uploadedFile.getFileName()));
		} catch (IOException e) {
			
			e.printStackTrace();
			
		}
        
        userBean.setOriImage(oriImage);
		
    }
    
    
    
	public void handleFileUpload(FileUploadEvent event) {
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		String IP = request.getRemoteAddr();
		System.out.println(IP);
		System.out.println(request.getRemoteUser());
		
    	UploadedFile uploadedFile = event.getFile();
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");  
        FacesContext.getCurrentInstance().addMessage(null, msg);
        
        
        String fileName = uploadedFile.getFileName();
        System.out.println("fileName is " + fileName);
        
        oriFile = uploadedFile.getContents();
        System.out.println(uploadedFile.getFileName() + " is uploaded");
        
        //DefaultStreamedContent enhanceImage = new ImageEnhanceController();
        try {
			InputStream stream = uploadedFile.getInputstream();
			System.out.println(uploadedFile.getContentType() + " is the type");
			file = new DefaultStreamedContent(stream, uploadedFile.getContentType(), uploadedFile.getFileName());
			enhanceImage = new DefaultStreamedContent(new ByteArrayInputStream(oriFile), uploadedFile.getContentType(), fileName);
			//enhanceImage.setOriImage(file);
			//enhanceImage.setEnhanceImage(file);
			//setImageEnhanceController(enhanceImage);
			
		} catch (IOException e) {
			
			e.printStackTrace();
		}  
    }  
	
	public void uploadVideo(FileUploadEvent event) {

		String filePath = FacesContext.getCurrentInstance().getExternalContext().getRealPath(File.separator + "upload");
		
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    	//HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    	userBean = (UserBean) FacesUtil.getManagedBean("userBean");	
		String IP = request.getRemoteAddr();
		
		userBean.setIP(IP);
		
		File directory = new File(filePath);
		
		if(!directory.exists()){
			directory.mkdir();
			System.out.println("Create filePath!");
		}
		
		//generate a random name for the original video
		double random = Math.random()*100;
		String videoName = event.getFile().getFileName();
		String vName = random + videoName.substring((videoName.lastIndexOf('\\')) + 1);
		System.out.println(videoName);
		String contentType = event.getFile().getContentType();
		//get the absolute path of video, used by MATLAB
		String wholePath = filePath + File.separator + vName;
		
		//String enWholePath = filePath + File.separator+"en" + vName;
		//String deWholePath = filePath + File.separator+"de" + vName;
		System.out.println("WholePath:" + wholePath);
		
		File file = new File(wholePath);
		InputStream inputStream = null;
		try {
			FileOutputStream outputStream = new FileOutputStream(file);
			
			inputStream = event.getFile().getInputstream();
			byte[] fileByte = new byte[100000000];
			
			
			int bulk;
			bulk = inputStream.read(fileByte);
			outputStream.write(fileByte, 0, bulk);
			
			inputStream.close();
			
			outputStream.flush();
			outputStream.close();
			
			
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		
		StreamedContent video = new DefaultStreamedContent(inputStream, contentType, vName);
		
		VideoBean oriVideo = new VideoBean();
		oriVideo.setWholePath(wholePath);
		oriVideo.setPath("upload\\" + vName);
		oriVideo.setVideo(video);
		oriVideo.setVideoName(vName);
		oriVideo.setFilePath(filePath);
		oriVideo.setRender(true);

		FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + "Video is uploaded.");
		FacesContext.getCurrentInstance().addMessage(null, msg);
		System.out.println("Video upload success!");
		
		videoPath = oriVideo.getPath();
		System.out.println("the path" +videoPath);
		
		userBean.setOriPath(videoPath);
		
		userBean.setOriVideo(oriVideo);
		
		
		
		//videoPath = wholePath;
//		File oriFile = new File(oriVideo.getWholePath());
//		File outFile = new File(enWholePath);
//		File deFile = new File(deWholePath);
//		
//        
//		
//		
//		try {
//			KeyGenerator kgen = KeyGenerator.getInstance("AES");
//	        //byte key[] = {0x00,0x32,0x22,0x11,0x00,0x00,0x00,0x00,0x00,0x23,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
//	        SecretKey skey = kgen.generateKey();
//	        System.out.println(skey.toString());
//			VideoProcess.encryptVideo(oriFile,skey,outFile);
//			System.out.println("encrypt success");
//			VideoProcess.decrptVideo(outFile,skey,deFile);
//			System.out.println("decrypt success");
//			System.out.println();
//		} catch (Exception e) {
//			
//			e.printStackTrace();
//		}
		System.out.println("the path" +videoPath);
	}
	
	
	
	public void enhanceImageOne(){
		System.out.println("enhance image");
		HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		FileUploadController f = (FileUploadController) session.getAttribute("fileUploadController");
		System.out.println(f.file.getName());
	}
	
	public StreamedContent downEnhanceImage(){
		HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		FileUploadController f = (FileUploadController) session.getAttribute("fileUploadController");
		
		return f.getFile();
	}
	
	public void downEnhanceVideo(){
		userBean = (UserBean) FacesUtil.getManagedBean("userBean");
		String name = userBean.getEnhanceVideo().getVideoName();
				
		InputStream stream = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/upload" + File.separator + name); 
		enhanceVideo = new DefaultStreamedContent(stream, "avi", name);
	}
}